package com.sync.syncmasterdata.product.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.customer.service.http.HttpAPIServiceForCrmSync;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.product.entity.amu8.AMInvFreeContrapose;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowDeleteEntity;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowEntity;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowReStoreEntity;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowUpdateEntity;
import com.sync.syncmasterdata.product.entity.u8.InvEx;
import com.sync.syncmasterdata.product.entity.u8.InvFreeContrapose;
import com.sync.syncmasterdata.product.entity.wms.EleProduct;
import com.sync.syncmasterdata.product.pojo.cp.InventoryForCP;
import com.sync.syncmasterdata.product.pojo.crm.InventoryForCrm;
import com.sync.syncmasterdata.product.pojo.crm.*;

import com.sync.syncmasterdata.product.pojo.erp.InventoryForU8;

import com.sync.syncmasterdata.product.pojo.gsp.InventoryForGsp;
import com.sync.syncmasterdata.product.pojo.oa.InventoryForOA;
import com.sync.syncmasterdata.product.repository.amu8.AMInvFreeContraposeRepository;
import com.sync.syncmasterdata.product.repository.oa.*;
import com.sync.syncmasterdata.product.repository.u8.ComputationunitRepository;
import com.sync.syncmasterdata.product.repository.u8.InvExRepository;
import com.sync.syncmasterdata.product.repository.u8.InvFreeContraposeRepository;
import com.sync.syncmasterdata.product.repository.u8.InventoryRepository;
import com.sync.syncmasterdata.util.AuthUtil;
import com.sync.syncmasterdata.util.NormalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.*;

import static com.sync.syncmasterdata.util.NormalUtil.getNowDataTime;

/**
 * 请求新增\修改U8产品信息,U8,crm,oa(取消)相关服务
 */
@Transactional
@Service
@Slf4j
public class SyncInventoryService {

    @Autowired
    private HttpAPIServiceForCrmSync httpAPIService;

    @Autowired
    private InventoryRepository inventoryRepository;
    @Autowired
    private InvFreeContraposeRepository invFreeContraposeRepository;

    @Autowired
    private AMInvFreeContraposeRepository amInvFreeContraposeRepository;

    @Autowired
    private InventoryWorkflowRepository inventoryWorkflowRepository;

    @Autowired
    private InventoryForUpdateWorkflowRepository inventoryForUpdateWorkflowRepository;
    @Autowired
    private InventoryForDeleteWorkflowRepository inventoryForDeleteWorkflowRepository;

    @Autowired
    private InventoryForReStoreWorkflowRepository inventoryForReStoreWorkflowRepository;

    @Autowired
    private UpdateChanpinbmRepository updateChanpinbmRepository;

    @Autowired
    private ComputationunitRepository computationunitRepository;

    @Autowired
    private InvExRepository invExRepository;

//    @Autowired
//    private ProductForWmsRepository productForWmsRepository;

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthUtil authUtil;
    @Autowired
    private DingRobotService dingRobotService;


    private static final String crmEntity = "new_products";
    @Value("${myprops.cpurl}")
    private String CPURL;

    /**
     * U8 openapi用 静态变量(配套 新增、更新用) @Value("${maycur.url}")
     */
    private final String FROM_ACCOUNT = "biosanu8";
    private final String TO_ACCOUNT = "biosanu8";
    @Value("${ukey.product_key}")
    private String PRODUCT_APP_KEY;
    @Value("${ukey.product_secret}")
    private String PRODUCT_APP_SECRET;

    @Value("${gsp.url}")
    private String GSPURL;
    private static String[] SUSER = {"15267167276"};


    /**
     * 获取u8openapi token
     *
     * @return
     */
    private String getTokendel() {
//        String app_secret="2f2f41680cb24288a3eb21ebc9da5da5";
        String requestUrl = String.format("%s%s?from_account=%s&app_key=%s&app_secret=%s", confInfo.getU8opeapiurl(), "system/token", FROM_ACCOUNT, PRODUCT_APP_KEY, PRODUCT_APP_SECRET);
        try {
            JSONObject jsonObject = new JSONObject(httpAPIService.doGet(requestUrl));
            if (jsonObject.get("errcode").equals("0")) {
                JSONObject responseStr = (JSONObject) jsonObject.get("token");
                return responseStr.get("id").toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 获取tradeid
     *
     * @param token
     * @return
     */
    private String getTradeid(String token) {
//        String app_secret="2f2f41680cb24288a3eb21ebc9da5da5";
        String requestUrl = String.format("%s%s?from_account=%s&app_key=%s&token=%s", confInfo.getU8opeapiurl(), "system/tradeid", FROM_ACCOUNT, PRODUCT_APP_KEY, token);
        try {
            JSONObject jsonObject = new JSONObject(httpAPIService.doGet(requestUrl));
            if (jsonObject.get("errcode").equals("0")) {
                JSONObject responseStr = (JSONObject) jsonObject.get("trade");
                return responseStr.get("id").toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 通过OpenAPI 获取 u8产品信息
     * @param sCode
     */
    public void getInvFromOpenU8(String sCode){
        String token = authUtil.getCPTokenByTag("u8prosync");
        String ds_s = "4";
        String requestUrl=confInfo.getU8opeapiurl() + "api/inventory/get?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s + "&id=" + sCode;
        try {
            String ret=httpAPIService.doGet(requestUrl);
            System.out.println("请求返回:"+ ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送U8产品信息，使用openapi
     */
    public String addInvToOpenU8(InventoryForU8 inventory, String ds_s) {
//        String token = getToken();
        String token = authUtil.getCPTokenByTag("u8prosync");
        String tradeid = getTradeid(token);
        //默认同步
        String sync = "1";
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/add?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s + "&tradeid=" + tradeid + "&sync=" + sync;
        log.info("U8新增产品URL----->{}", requestUrl);
        try {
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("inventory", inventory);
            String requestEntity = objectMapper.writeValueAsString(tmpMap);
            log.info("请求erp 新建 传入json：" + requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);
            log.info("请求erp 新建 返回:{}", responseStr);
            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.getString("errcode").equals("0")) {
                //成功
                log.info("产品同步成功--用友接口返回：{}", responseStr);

                return jsonObject.get("id").toString();
            } else {
                //失败 钉钉提示
                log.info("产品同步失败--用友接口返回：{}", jsonObject.toString());
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 更新U8产品 使用openapi
     *
     * @param inventory
     * @param ds_s
     * @return
     */
    public String editInvToOpenU8(InventoryForU8 inventory, String ds_s) {
        String token = authUtil.getCPTokenByTag("u8prosync");

        //默认同步
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/edit?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s;

        try {
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("inventory", inventory);
            String requestEntity = objectMapper.writeValueAsString(tmpMap);
            log.info("请求erp 更新 传入json：" + requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);

            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                //成功
                return jsonObject.get("id").toString();
            } else {
                //失败 钉钉提示
                log.info("产品同步--用友接口返回：{}", jsonObject.toString());
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 停用 U8产品 使用openapi
     *
     * @param productCode
     * @param ds_s
     * @return
     */
    public String delInvToOpenU8(String productCode, String ds_s) {
        String token = authUtil.getCPTokenByTag("u8prosync");
        //默认同步
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/edit?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s;

        try {
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("code", productCode);
            objMap.put("end_date", getNowDataTime());
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("inventory", objMap);
            String requestEntity = objectMapper.writeValueAsString(tmpMap);
            log.info("请求erp 更新 传入json：" + requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);

            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                //成功
                return jsonObject.get("id").toString();
            } else {
                //失败 钉钉提示
                log.info("产品同步--用友接口返回：{}", jsonObject.toString());
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 复用(反停用) U8产品 使用openapi 包含下次停用时间
     *
     * @param entity
     * @param ds_s
     * @return
     */
    public String reStoreInvToOpenU8ByNextTime(ProductWorkflowReStoreEntity entity, String ds_s) {
        String token = authUtil.getCPTokenByTag("u8prosync");
        //默认同步
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/edit?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s;

        try {
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("code", entity.getInventory_code());
            objMap.put("end_date", entity.getNext_downtime());
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("inventory", objMap);
            String requestEntity = objectMapper.writeValueAsString(tmpMap);
            log.info("请求erp 更新 传入json：" + requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);

            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                //成功
                return jsonObject.get("id").toString();
            } else {
                //失败 钉钉提示
                log.info("产品同步--用友接口返回：{}", jsonObject.toString());
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    /**
     * 复用(反停用) U8产品 使用openapi
     *
     * @param entity
     * @param ds_s
     * @return
     */
    public String reStoreInvToOpenU8(ProductWorkflowReStoreEntity entity, String ds_s) {
        String token = authUtil.getCPTokenByTag("u8prosync");
        //默认同步
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/edit?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s;

        try {
            Map<String, Object> objMap = new HashMap<>();
            objMap.put("code", entity.getInventory_code());
            objMap.put("end_date","");
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("inventory", objMap);
            String requestEntity = objectMapper.writeValueAsString(tmpMap);
            log.info("请求erp 更新 传入json：" + requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);

            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                //成功
                return jsonObject.get("id").toString();
            } else {
                //失败 钉钉提示
                log.info("产品同步--用友接口返回：{}", jsonObject.toString());
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //请求新增CRM产品对象

    /**
     * 请求 新增crm 产品信息
     *
     * @param inventoryForCrm
     * @return
     */
    public String addInvToCrm(InventoryForCrm inventoryForCrm) {
//        final String crmEntity = "new_products";
        String requestUrl = String.format("%s%s", this.confInfo.getCrmurl(), crmEntity);

        try {
            log.info("Crm新增待请求字符串:" + objectMapper.writeValueAsString(inventoryForCrm));
            String responseStr = httpAPIService.doPostCrm(requestUrl, objectMapper.writeValueAsString(inventoryForCrm));

            ResponseInventoryForCrm responseInventoryForCrm = objectMapper.readValue(responseStr, ResponseInventoryForCrm.class);
            String new_productid = responseInventoryForCrm.getNew_erp_productid();
            if (new_productid != null) {
                return new_productid;
            } else {
                //失败
                log.info("Crm请求返回：{}", objectMapper.writeValueAsString(responseInventoryForCrm));
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    /**
     * 请求新增 Gsp 产品信息
     */
    public String addInvToGsp(InventoryForGsp inventoryForGsp) {
        String url = GSPURL + "/ts/openapi/putGood";
        List<InventoryForGsp> list = new ArrayList<>();
        list.add(inventoryForGsp);
        Map<String,Object> reqJson = new HashMap<>();
        reqJson.put("bscArch", list);
        try {
            //请求推送
            RestTemplate restTemplate = new RestTemplate();
            //中文乱码问题
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            log.info("请求报文---->{}", objectMapper.writeValueAsString(reqJson));
//        HttpEntity<Map<String, Object>> request = new HttpEntity<>(reqJson, headers);
            String resJson = restTemplate.postForObject(url, reqJson ,String.class);
            JSONObject _json = new JSONObject(resJson);
            JSONObject _json2=_json.getJSONObject("fluxredt");
            _json2.get("returnFlag");
            if(_json2.getString("returnFlag").equals("1")){
                log.info("增加GSP 产品信息-------->成功");
                return "1";
            }else{
                log.info("增加GSP 产品信息-------->失败---->{}", resJson);
                return "0";
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 请求 修改crm产品对象
     * @param inventoryForCrm
     * @return
     */
    public String editInvToCrm(InventoryForCrm inventoryForCrm, String guid) {
        String requestUrl = String.format("%s%s(%s)", this.confInfo.getCrmurl(), crmEntity, guid);
        try {
            log.info("产品推送--Crm更新待请求字符串:" + objectMapper.writeValueAsString(inventoryForCrm));
            String responseStr = httpAPIService.doUpdateCrm(requestUrl, objectMapper.writeValueAsString(inventoryForCrm));
            ResponseInventoryForCrm responseInventoryForCrm = objectMapper.readValue(responseStr, ResponseInventoryForCrm.class);
            String new_productid = responseInventoryForCrm.getNew_erp_productid();
            if (new_productid != null) {
                //成功
                return new_productid;
            } else {
                //失败
                log.info("Crm请求返回：{}", objectMapper.writeValueAsString(responseInventoryForCrm));
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 请求 修改crm产品对象
     * @param guid
     * @return
     */
    public String delInvToCrm(String guid) {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        String requestUrl = String.format("%s%s(%s)", this.confInfo.getCrmurl(), crmEntity, guid);
        try {
            log.info("产品推送--Crm 停用 待请求字符串:" + guid);
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("statecode",1);
            String responseStr = httpAPIService.doUpdateCrm(requestUrl, objectMapper.writeValueAsString(reqMap));
            ResponseInventoryForCrm responseInventoryForCrm = objectMapper.readValue(responseStr, ResponseInventoryForCrm.class);
            String new_productid = responseInventoryForCrm.getNew_erp_productid();
            if (new_productid != null) {
                //成功
                return new_productid;
            } else {
                //失败
                log.info("Crm请求返回：{}", objectMapper.writeValueAsString(responseInventoryForCrm));
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 请求 恢复crm产品对象
     * @param guid
     * @return
     */
    public String reStoreInvToCrm(String guid) {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        String requestUrl = String.format("%s%s(%s)", this.confInfo.getCrmurl(), crmEntity, guid);
        try {
            log.info("产品推送--Crm 停用 待请求字符串:" + guid);
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("statecode",0);
            String responseStr = httpAPIService.doUpdateCrm(requestUrl, objectMapper.writeValueAsString(reqMap));
            ResponseInventoryForCrm responseInventoryForCrm = objectMapper.readValue(responseStr, ResponseInventoryForCrm.class);
            String new_productid = responseInventoryForCrm.getNew_erp_productid();
            if (new_productid != null) {
                //成功
                return new_productid;
            } else {
                //失败
                log.info("Crm请求返回：{}", objectMapper.writeValueAsString(responseInventoryForCrm));
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    /**
     * 新增中台 存货档案
     *
     * @return
     */
    public String addInvToCP(InventoryForCP cp) {
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/addProduct");
        String oid = "";
        try {
            System.out.println("请求cp报文打印："+objectMapper.writeValueAsString(cp));
            oid = httpAPIService.doPost(requestUrl, objectMapper.writeValueAsString(cp));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return oid;

    }

    /**
     * 更新中台 存货档案数据
     */
    public String editInvToCP(InventoryForCP cp){
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/editProduct");
        String oid = "";
        try {
            System.out.println("请求cp报文打印："+objectMapper.writeValueAsString(cp));
            oid = httpAPIService.doPost(requestUrl, objectMapper.writeValueAsString(cp));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return oid;
    }

    /**
     * 用于 获取中台的产品价格维护档案对应code 的 id (chanpinbjwh)
     * @param invCode
     * @return
     */
    private String getInvIdToCPOffer(String invCode){
//        String requestUrl = String.format("%s%s", this.CPURL, "/api/integration/bpmObjectCompile/backEnd/getObjectInstanceByKV?schemaCode=chanpinbjwh&filterKey=chanpinbh&filterValue=" + invCode);
        String requestUrl2 = String.format("%s%s", this.CPURL, "/api/integration/bpmObjectCompile/backEnd/getObjectInstanceByKVs?schemaCode=chanpinbjwh");
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("chanpinbh", invCode);
        reqMap.put("zhuangtai", "0");
        RestTemplate restTemplate = new RestTemplate();
        //中文乱码问题
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
        String resJson = restTemplate.postForObject(requestUrl2, reqMap ,String.class);
        JSONObject json1 = new JSONObject(resJson);
        JSONObject json2 = json1.getJSONObject("data");
        if(json2.getInt("code")==0){
            //请求成功
            JSONObject resultJson = json2.getJSONObject("result");
            if(resultJson.getInt("total")==1){
                JSONArray array=resultJson.getJSONArray("content");
                JSONObject retJson = (JSONObject) array.get(0);
                String oid = retJson.getString("id");
                return oid;
            }else if (resultJson.getInt("total")==0){
                return "-2 BPM OFFER档案中没有改产品,不用修改Offer档案";
            }else{
                return "-3 BPM OFFER档案记录数量(有多条数据)异常";    //返回值异常 一般是BPM中的记录有问题
            }

        }else{
            return "-1 BPM OFFER档案调用方法异常";        //请求异常
        }
    }

    /**
     * 用于 更新中台 报价维护器 对应产品的属性
     * @param cp
     * @return
     */
    public String editOfferInvToCP(InventoryForCP cp) {
        String code = cp.getCunhuobm();
        String oid=getInvIdToCPOffer(code);
        if(oid.contains("-1")||oid.contains("-3")||oid.contains("-2")){
            log.info("更新处理------>{}", oid);
            return oid;
        }

        try {
            String requestUrl = String.format("%s%s",this.CPURL, "/api/integration/bpmObjectCompile/backEnd/updateObjectInstance");
            RestTemplate restTemplate = new RestTemplate();
            //中文乱码问题
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("schemaCode","chanpinbjwh");
            JSONObject reqJson = new JSONObject();
            reqJson.put("id", oid);
            reqJson.put("huohao", cp.getHuohao());
            reqJson.put("guige", cp.getGuigexh());
            reqJson.put("pinpai", cp.getPinpaiwb());
            reqJson.put("chanpinmc", cp.getChanpinmc());

            HttpEntity<String> reqEntity = new HttpEntity<>(reqJson.toString(), headers);
            String resJson = restTemplate.postForObject(requestUrl, reqEntity, String.class);
            //更新 标准套 中的对应数据项
            reqJson.put("cunhuobm", cp.getCunhuobm());
            reqJson.put("huowumc", cp.getChanpinmc());
            String requestUrl2=String.format("%s%s",this.CPURL,"/api/presale/customiz/backEnd/standardGroup/updateStandardGroupProduct");
            HttpEntity<String> reqEntity2 = new HttpEntity<>(reqJson.toString(), headers);
            restTemplate.postForObject(requestUrl2, reqEntity2, String.class);
            log.info("用于 更新中台 报价维护器 对应产品的属性 请求返回------->{}", resJson.toString());
            return "0";
        } catch (Exception e) {
            return "-1 BPM editOfferInvToCP 处理异常";
        }
    }

    /**
     * 更新中台  存货档案数据 停用
     */
    public String delInvToCP(String cpId){
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/editProduct");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("id", cpId);
        reqMap.put("productStatus", true);

        String oid = "";
        try {
            System.out.println("请求cp报文打印："+objectMapper.writeValueAsString(reqMap));
            oid = httpAPIService.doPost(requestUrl, objectMapper.writeValueAsString(reqMap));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return oid;
    }

    /**
     * 更新中台  存货档案数据 恢复产品状态
     */
    public String reStoreInvToCP(String cpId){
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/editProduct");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("id", cpId);
        reqMap.put("productStatus", false);

        String oid = "";
        try {
            System.out.println("请求cp报文打印："+objectMapper.writeValueAsString(reqMap));
            oid = httpAPIService.doPost(requestUrl, objectMapper.writeValueAsString(reqMap));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return oid;
    }

    /**
     * 更新中台 报价维护器 对应产品停用
     */
    public String delInvToCPOfferProduct(String productCode){
        StringBuilder sb = new StringBuilder();
        //1.先请求获取对应的id
        String req1=String.format("%s%s",this.CPURL,"api/integration/bpmObjectCompile/backEnd/getObjectInstanceByKV?schemaCode=chanpinbjwh&filterKey=chanpinbh&filterValue="+productCode);
        try {
            String ret1=httpAPIService.doPost(req1, null);
            JSONObject json1 = new JSONObject(ret1);
            if(json1.getJSONObject("data").getJSONObject("result").getInt("total")>1){
                sb.append("修改产品报价记录存在多条，需要调整(已经全部停用)\n");
            }
            if(json1.getJSONObject("data").getJSONObject("result").getInt("total")==0){
                sb.append("找不到记录，不停用\n");
                return sb.toString();
            }
            JSONArray contentArray=json1.getJSONObject("data").getJSONObject("result").getJSONArray("content");
            List<String> bpmIds = new ArrayList<>();
            for (int i = 0; i < contentArray.length(); i++) {
                JSONObject __jsonObj=contentArray.getJSONObject(i);

                bpmIds.add(__jsonObj.getString("id"));
            }

            //根据ids 进行productOffer的停用
            String req2 = String.format("%s%s", this.CPURL, "/api/integration/bpmObjectCompile/backEnd/updateObjectInstance");
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("schemaCode","chanpinbjwh");
            for (String id : bpmIds) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("zhuangtai", true);
                String ret=httpAPIService.doPostSelfHeader(req2, objectMapper.writeValueAsString(map), headerMap);
                sb.append(ret);
                sb.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("更新 产品报价器异常！！！！联系管理员检查");
            return "更新 产品报价器异常！！！！联系管理员检查";
        }
        return sb.toString();

    }



    /**
     * 新增 wms 产品对象
     * 婓创GSP取消
     */
    @Deprecated
    public String addInvToWms(EleProduct product) {
        //先检查编号是否重复
        String code = product.getSCode();
//        EleProduct _ele1 = productForWmsRepository.findProductByCode(code);
        EleProduct _ele1 = null;

        if (_ele1==null) {
            //不存在
            log.info("wms:{} 产品不存在，准备插入", product.getSCode());
            product.setUGuid1(NormalUtil.getUpperGuid());
            product.setTCrtDate(NormalUtil.getNowTime());
//            EleProduct _ele2=productForWmsRepository.save(product);
            EleProduct _ele2=null;
            log.info("新增的wms对象：{}", _ele2.toString());
            return _ele2.getUGuid1();
        } else {
            return "-5";
        }
    }

    /**
     * 通过数据库 补充 产品的自由项
     */
    public void addInvFree(InvFreeContrapose invFreeContrapose) {
        InvFreeContrapose inv = invFreeContraposeRepository.save(invFreeContrapose);
        log.info("插入 自由项成功:" + inv.getCInvFreeGUID());
    }
    /**
     * 通过数据库 补充 安迈u8产品的自由项
     */
    public void addAMU8InvFree(AMInvFreeContrapose invFreeContrapose) {
        AMInvFreeContrapose inv = amInvFreeContraposeRepository.save(invFreeContrapose);
        log.info("插入 安迈U8自由项成功:" + inv.getCInvFreeGUID());
    }


    /**
     * 通过数据库 补充 产品档案的自定义字段
     */
    public void addInvEx(InvEx invEx) {
        InvEx invEx1 = invExRepository.save(invEx);
        log.info("成功插入产品扩展表:{}", invEx1);
    }
    public void addInvExFor170(InvEx invEx) {
        invExRepository.save170(invEx.getCInvCode(),invEx.getCidefine2(),invEx.getCidefine3(),invEx.getCidefine4(),invEx.getCidefine5(),invEx.getCidefine6());
        log.info("成功插入产品扩展表(170)");
    }

    /**
     * 通过数据库 更新 产品档案的自定义字段
     */
    public void updateInvEx(InvEx invEx){
        invExRepository.updateInvEx(invEx.getCInvCode(), invEx.getCidefine2(), invEx.getCidefine3(), invEx.getCidefine4(), invEx.getCidefine5());
        log.info("更新产品信息完成(111)");
    }


    /**
     * 获取产品分类下，最后一个可用编码
     * 返回-1，异常报错
     *
     * @return
     */
//    public String getLastCode(String sort) {
//        try {
//            Inventory inventory = this.inventoryRepository.findLatestBycinvCCode(sort,sort.length());
//            if (inventory == null) {
//                return sort + "0001";
//            }
//            log.info("获取到的最后一个产品编号为:" + inventory.getCInvCode() + "产品类型:" + inventory.getCInvCCode());
//            //处理字符串
//            String code = inventory.getCInvCode();
//            int codeOrder = 0;
//            codeOrder = Integer.valueOf(code.substring(4, code.length()));
//            //成功转换
//            int newCodeOrder = codeOrder + 1;
//            String returnCode = new DecimalFormat("0000").format(newCodeOrder);
//            return sort + returnCode;
//        } catch (Exception ex) {
//            log.error(ex.toString());
//            return "-1";
//        }
//    }

    /**
     * 获取产品分类下，最后一个可用编码 不采用排序的方法,计算
     * 返回-1，异常报错
     *
     * @return
     */
    public String getLastCode(String sort) {
        try {
            List<String> list = this.inventoryRepository.findBycinvcCode(sort,sort.length());
            if (Objects.isNull(list)) {
                return sort + "0001";
            }

            //处理字符串
            List<Integer> listInt = new ArrayList<>();
            for (String s : list) {
                listInt.add(stringToInt(s));
            }
            listInt.sort((o1, o2) -> -1*o1.compareTo(o2));  //成功转换
            log.info("listInt---->{}", listInt.toString());
            int newCodeOrder = listInt.get(0) + 1;
            String returnCode = new DecimalFormat("0000").format(newCodeOrder);
            return sort + returnCode;
        } catch (Exception ex) {
            log.error(ex.toString());
            return "-1";
        }
    }
    private int stringToInt(String s) {
        try {
            return Integer.valueOf(s);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取oa流程中需要新增的产品信息
     */
    public List<InventoryForOA> getWorkflowInfo(String requestid) {

        List<ProductWorkflowEntity> productWorkflowEntities = inventoryWorkflowRepository.getProductWorkFlowEntitys(requestid);
        try {
            log.info("----从数据库中获取OA申请产品流程明细-----{}", objectMapper.writeValueAsString(productWorkflowEntities));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (productWorkflowEntities.isEmpty()) {
            return null;
        }
        //entity 转 pojo
        List<InventoryForOA> inventoryForOAs = new ArrayList<>();
        for (ProductWorkflowEntity entity : productWorkflowEntities) {

            InventoryForOA oa = new InventoryForOA();
            oa.setId(entity.getId());
            oa.setTongyongmc(entity.getTongyongmc());
            oa.setKuwei(entity.getKuweiwb());
            oa.setChanpinlx(entity.getChanpinlx());
            oa.setCunhuobm(entity.getCunhuobm());
            oa.setChanpinmc(entity.getChanpinmc());
            oa.setHuohao(entity.getHuohao());
            oa.setGuigexh(entity.getGuigexh());
            oa.setZhujildw(entity.getZhujildw());
            oa.setPinpaiwb(entity.getPinpai());
            oa.setShengchanqy(entity.getShengchanqy());
            oa.setShengchanqywb(entity.getShengchanqywb());
            oa.setGuochanjk(entity.getGuochanjk());
            oa.setYewulx(entity.getYewulx());
            oa.setChanpinx(entity.getChanpinx());
            oa.setChanpinz(entity.getChanpinz());
            oa.setXiangmumc(entity.getXiangmumc());
            oa.setXiangmumcwb(entity.getXiangmumcwb());
            oa.setBeizhu(entity.getBeizhu());
            oa.setShifouylqx(entity.getShifouylqx());
            oa.setShifoucgbh(entity.getShifoucggh());
            oa.setJiancexmh(entity.getJiancexmh());
            //wms专用
            oa.setShifouts(entity.getShifouts());
            oa.setShifoucw(entity.getShifoucw());
            oa.setTingshou(entity.getTingshou());
            oa.setWenduc(entity.getWenduc());
            oa.setWenduz(entity.getWenduz());
            oa.setYujingyxq(entity.getYujingyxq());
            oa.setYouxiaoq(entity.getYouxiaoq());
            oa.setYanghulx(entity.getYanghulx());
            oa.setStoreType(entity.getStoreType());
            oa.setStoreType1(entity.getStoreType1());

            //wms多温度
            oa.setZixiangmc(entity.getZixiangmc());
            oa.setWenduc1(entity.getWenduc1());
            oa.setWenduz1(entity.getWenduz1());

            //增加unitName
            String unitName = computationunitRepository.getUnitName(entity.getZhujildw());
            oa.setUnitName(unitName);

            inventoryForOAs.add(oa);
        }
        return inventoryForOAs;
    }


    /**
     * 获取oa流程中需要新增的产品信息 by 货号单条
     */
    public List<InventoryForOA> getWorkflowInfo(String requestid,String huohao) {

        List<ProductWorkflowEntity> productWorkflowEntities = inventoryWorkflowRepository.getProductWorkFlowEntitysByhuohao(requestid,huohao);
        try {
            log.info("---------{}", objectMapper.writeValueAsString(productWorkflowEntities));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (productWorkflowEntities.isEmpty()) {
            return null;
        }
        //entity 转 pojo
        List<InventoryForOA> inventoryForOAs = new ArrayList<>();
        for (ProductWorkflowEntity entity : productWorkflowEntities) {

            InventoryForOA oa = new InventoryForOA();
            oa.setId(entity.getId());
            oa.setTongyongmc(entity.getTongyongmc());
            oa.setKuwei(entity.getKuweiwb());
            oa.setChanpinlx(entity.getChanpinlx());
            oa.setCunhuobm(entity.getCunhuobm());
            oa.setChanpinmc(entity.getChanpinmc());
            oa.setHuohao(entity.getHuohao());
            oa.setGuigexh(entity.getGuigexh());
            oa.setZhujildw(entity.getZhujildw());
            oa.setPinpaiwb(entity.getPinpai());
            oa.setShengchanqy(entity.getShengchanqy());
            oa.setShengchanqywb(entity.getShengchanqywb());
            oa.setGuochanjk(entity.getGuochanjk());
            oa.setYewulx(entity.getYewulx());
            oa.setChanpinx(entity.getChanpinx());
            oa.setChanpinz(entity.getChanpinz());
            oa.setXiangmumc(entity.getXiangmumc());
            oa.setXiangmumcwb(entity.getXiangmumcwb());
            oa.setBeizhu(entity.getBeizhu());
            oa.setShifouylqx(entity.getShifouylqx());
            oa.setShifoucgbh(entity.getShifoucggh());
            oa.setJiancexmh(entity.getJiancexmh());
            oa.setStoreType(entity.getStoreType());
            //wms专用
            oa.setShifouts(entity.getShifouts());
            oa.setShifoucw(entity.getShifoucw());
            oa.setTingshou(entity.getTingshou());
            oa.setWenduc(entity.getWenduc());
            oa.setWenduz(entity.getWenduz());
            oa.setYujingyxq(entity.getYujingyxq());
            oa.setYouxiaoq(entity.getYouxiaoq());
            oa.setYanghulx(entity.getYanghulx());
            //wms多温度
            oa.setZixiangmc(entity.getZixiangmc());
            oa.setWenduc1(entity.getWenduc1());
            oa.setWenduz1(entity.getWenduz1());

            //增加unitName
            String unitName = computationunitRepository.getUnitName(entity.getZhujildw());
            oa.setUnitName(unitName);

            inventoryForOAs.add(oa);
        }
        return inventoryForOAs;
    }

    /**
     * 通过流程 修改产品信息
     */
    public List<InventoryForOA> getWorkflowInfoForUpdate(String requestid) {

        List<ProductWorkflowUpdateEntity> productWorkflowEntityForUpdates = inventoryForUpdateWorkflowRepository.getProductWorkflowEntityForUpdate(requestid);
        try {
            log.info("---------{}", objectMapper.writeValueAsString(productWorkflowEntityForUpdates));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (productWorkflowEntityForUpdates.isEmpty()) {
            return null;
        }
        //entity 转 pojo
        List<InventoryForOA> inventoryForOAs = new ArrayList<>();
        for (ProductWorkflowUpdateEntity entity : productWorkflowEntityForUpdates) {

            InventoryForOA oa = new InventoryForOA();
            //数据库id
            oa.setId(entity.getId());
            //存货编码
            oa.setCunhuobm(entity.getCunhuobm());
            //通用名称
            oa.setTongyongmc(entity.getTongyongmc());
            //库位
            oa.setKuwei(entity.getKuweiwb());
            //产品名称
            oa.setChanpinmc(entity.getChanpinmc());
            //产品货号
            oa.setHuohao(entity.getHuohao());
            //规格型号
            oa.setGuigexh(entity.getGuigexh());
            //品牌文本
            oa.setPinpaiwb(entity.getPinpai());
            //生产企业（U8供应商id）
            oa.setShengchanqy(entity.getShengchanqy());
            //生产企业文本
            oa.setShengchanqywb(entity.getShengchanqywb());
            //国产进口
            oa.setGuochanjk(entity.getGuochanjk());
            //备注
            oa.setBeizhu(entity.getBeizhu());
            //是否医疗器械
            oa.setShifouylqx(entity.getShifouylqx());
            //是否常规备货
            oa.setShifoucgbh(entity.getShifoucggh());
            //项目部分
            oa.setYewulx(entity.getYewulx());
            oa.setChanpinx(entity.getChanpinx());
            oa.setChanpinz(entity.getChanpinz());
            oa.setXiangmumc(entity.getXiangmumc());
            oa.setXiangmumcwb(entity.getXiangmumcwb());
            //crmid cpid部分
            oa.setCrmid(entity.getCrmid());
            oa.setCpid(entity.getCpid());

            inventoryForOAs.add(oa);
        }
        return inventoryForOAs;
    }

    /**
     * 通过流程 转化 需要停用的产品信息
     */
    public List<ProductWorkflowDeleteEntity> getWorkflowInfoforDelete(String requestid) {
        List<ProductWorkflowDeleteEntity> list=inventoryForDeleteWorkflowRepository.getProductWorkflowEntityForDelete(requestid);
        if (Objects.isNull(list)) {
            return null;
        }
        return list;
    }

    /**
     * 转化 需要复用的产品信息
     */
    public List<ProductWorkflowReStoreEntity> getWorkflowInfoforReStore(String requestid) {
        List<ProductWorkflowReStoreEntity> list=inventoryForReStoreWorkflowRepository.getProductWorkflowEntityForReStore(requestid);
        if (Objects.isNull(list)) {
            return null;
        }
        return list;
    }

    /**
     * 更新oa流程明细存货编码
     * @param id
     * @param cuohuomb
     */
    public void updateProductResult(Integer id, String cuohuomb) {
        if (id == null) {
            return;
        }
        updateChanpinbmRepository.updateProductWF(id,cuohuomb);
        log.info("更新oa流程明细记录成功id-{},code-{}",id,cuohuomb);
    }
}
